package com.tfjybj.itoo.teach.provider.service.impl;

import org.apache.dubbo.config.annotation.Reference;;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.dmsdbj.itoo.authorizationManagement.entity.OrganizationEntity;
import com.dmsdbj.itoo.authorizationManagement.facade.OrganizationFacade;
import com.dmsdbj.itoo.tool.base.service.impl.BaseServicePlusImpl;
import com.dmsdbj.itoo.tool.business.ItooResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tfjybj.itoo.teach.entity.InstitutionEntity;
import com.tfjybj.itoo.teach.model.InstitutionModel;
import com.tfjybj.itoo.teach.provider.dao.InstitutionDao;
import com.tfjybj.itoo.teach.provider.service.InstitutionService;
import com.tfjybj.itoo.teach.template.InstitutionExportTemplate;
import com.tfjybj.itoo.teach.template.InstitutionTemplate;
import lombok.extern.slf4j.Slf4j;
import org.jplus.hyberbin.excel.utils.ExcelUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.*;

import static com.tfjybj.itoo.teach.provider.until.DemoConstants.*;

/**
 * InstitutionService接口实现类
 * ${base}表
 *
 * @author 田成荣
 * @version 2.0.0
 * @since 2.0.0 2018-11-08 19:34:10
 */
@Service("institutionService")
@Slf4j
public class InstitutionServiceImpl extends BaseServicePlusImpl<InstitutionDao, InstitutionEntity> implements InstitutionService {

    @Resource
    private InstitutionService institutionService;

    @Resource
    private RedisTemplate<String, InstitutionTemplate> redisTemplate;

    //@Autowired(required = false)
    //private OrganizationFacade organizationFacade;

	//region 模板生成
    @Resource
    private InstitutionDao institutionDao;
	
	 @Override
    public PageInfo<InstitutionEntity> queryByLikeName(String name, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(institutionDao.queryLikeName(name));
    }
	//endregion

    /* **********************************以下为非模板生成的内容********************************* */
    /**
     * 查询所有党政部门
     * @return Institution
     * @author 杨燕梅
     * @since 2.0.0 2018-11-23 17:20:53
     */
    @Override
    public List<InstitutionModel>queryAllInstitution(){
        return institutionDao.queryAllInstitution();
    }

    /**
     * 查询所有党政部门（带分页）
     * @author 杨燕梅
     * @since 2.0.0 2018-12-19 16:12:30
     */
    @Override
    public PageInfo<InstitutionModel> queryAllInstitutionPageInfo(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(institutionDao.queryAllInstitutionPageInfo());
    }
    /**
     * 根据名称查ID（学院和机构）-张家豪
     * @return Institution
     * @author 杨燕梅
     * @since 2.0.0 2018-11-25 16:00:30
     */
    @Override
    public List<InstitutionModel>queryAcademyAndInstitutionIdByName(String id){
        return institutionDao.queryAcademyAndInstitutionIdByName(id);
    }

    /**
     * 根据党政部门名称模糊查询institution(带分页)
     * @param searchContent  党政部门名称
     * @param pageNum   页码
     * @param pageSize 页数
     * @return 模糊查询的institution
     * @author 杨燕梅
     * @since 2.0.0 2018-12-8 11:21:06
     */
    @Override
    public PageInfo<InstitutionModel> queryInstitutionByLikeName(String searchContent, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(institutionDao.queryInstitutionByLikeName(searchContent.trim()));
    }

    /**
     * 根据党政部门ID查询党政部门详情
     *
     * @param idList 党政部门ID
     * @return 党政部门实体集合
     * @author 杨燕梅
     * @since 2.0.0 2018-12-12 19:48:32
     */
    @Override
    public List<InstitutionModel> queryInstitutionById(List<String> idList) {
        return institutionDao.queryInstitutionById(idList);
    }

    /**
     * 根据ID导出党政部门信息
     *
     * @param response 响应
     * @param idList   党政部门ID
     * @return 导出结果信息
     * @author 杨燕梅
     * @since 2.0.0 2018-12-12 19:48:40
     */
    @Override
    public ItooResult exportByInstitutionId(HttpServletResponse response, List<String> idList) {
        Map<Serializable, Serializable> map = new HashMap<>(16);

        map.put(SHEET_NAME, "导出的党政部门信息");
        //要导出的字段
        map.put(COLUMNS, new String[]{"code", "name", "abbreviation", "remark"});
        //导出表格的标题
        map.put(TITLE, "导出的党政部门信息");
        map.put(NAME, "导出的党政部门信息");
        //要导出的数据
        List<InstitutionExportTemplate> institutionExportTemplateList = new ArrayList<>();

        List<InstitutionModel> institutionModelList = institutionDao.queryInstitutionById(idList);
        for (InstitutionModel institutionModel : institutionModelList) {
            InstitutionExportTemplate institutionExportTemplate = new InstitutionExportTemplate();
            BeanUtils.copyProperties(institutionModel, institutionExportTemplate);
            institutionExportTemplateList.add(institutionExportTemplate);
        }
        //为空不进行导出
        if (CollectionUtils.isEmpty(institutionExportTemplateList)) {
            return ItooResult.build(ItooResult.FAIL, "没有要导出的数据！");
        }
        map.put(DATA_LIST, (Serializable) institutionExportTemplateList);
        //导出
        try {
            ExcelUtil.exportExcel(map, response);
        } catch (Exception e) {
            log.error("导出失败,未知的异常--" + e);
            return ItooResult.build(ItooResult.FAIL, "导出信息失败！", e);
        }
        return ItooResult.build(ItooResult.SUCCESS, "导出信息成功！");
    }

    /**
     * 根据条件导出党政部门
     *
     * @param response     响应
     * @param searchContent    党政部门名称
     * @return 导出结果信息
     * @author 杨燕梅
     * @since 2.0.0 2018-12-23 15:57:02
     */
    @Override
    public ItooResult exportByStrLike(HttpServletResponse response, String searchContent) {
        Map<Serializable, Serializable> map = new HashMap<>(16);

        map.put(SHEET_NAME, "党政部门");
        //要导出的字段
        map.put(COLUMNS,  new String[]{"code", "name", "abbreviation", "remark"});
        //导出表格的标题
        map.put(TITLE, "党政部门信息");
        map.put(NAME, "按条件导出的党政部门信息");
        //要导出的数据
        List<InstitutionExportTemplate> institutionExportTemplateList = new ArrayList<>();
        List<InstitutionModel> institutionModelList = institutionDao.queryInstitutionByLikeName(searchContent);
        for (InstitutionModel institutionModel : institutionModelList) {
            InstitutionExportTemplate institutionExportTemplate = new InstitutionExportTemplate();
            BeanUtils.copyProperties(institutionModel, institutionExportTemplate);
            institutionExportTemplateList.add(institutionExportTemplate);
        }
        //为空不进行导出
        if (CollectionUtils.isEmpty(institutionExportTemplateList)) {
            return ItooResult.build(ItooResult.FAIL, "没有要导出的数据！");
        }
        map.put(DATA_LIST, (Serializable) institutionExportTemplateList);

        //导出
        try {
            ExcelUtil.exportExcel(map, response);
        } catch (Exception e) {
            log.error("导出失败,未知的异常--" + e);
            return ItooResult.build(ItooResult.FAIL, "导出信息失败！", e);
        }
        return ItooResult.build(ItooResult.SUCCESS, "导出信息成功！");
    }

    /**
     * 下载党政部门模板，批量导入使用
     *
     * @param response 响应
     * @return 下载模板是否成功
     * @author 杨燕梅
     * @since 2.0.0 2018-11-30 10:10:17
     */
    @Override
    public boolean downLoadTemplate(HttpServletResponse response) {
        Map<Serializable, Serializable> map = new HashMap<>(16);
        List<InstitutionTemplate> templateList = new ArrayList<>();
        InstitutionTemplate institutionTemplate = new InstitutionTemplate();
        institutionTemplate.setCode("20");
        institutionTemplate.setName("办公室");
        institutionTemplate.setAbbreviation("办公室");
        institutionTemplate.setRemark("导入数据模板");
        templateList.add(institutionTemplate);
        //sheet的名字
        map.put(SHEET_NAME, "党政部门信息");
        //需要导入的字段
        map.put(COLUMNS,   new String[]{"code", "name", "abbreviation", "remark"});
        //表格的标题
        map.put(TITLE, "党政部门信息");
        map.put(NAME, "党政部门信息模板");
        map.put(DATA_LIST, (Serializable) templateList);
        try {
            ExcelUtil.exportExcel(map, response);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 批量导入党政部门
     * @param multipartFile
     * @param request
     * @param response
     * @return
     *  @author 杨燕梅
     *  * @since 2.0.0 2018-11-30 11:25:48
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ItooResult importTemplate(MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("UTF-8");
        try {
            //校验文件是否存在
            String fileName = multipartFile.getOriginalFilename();
            if (fileName == null) {
                log.error("导入失败,fileName is null!");
                return ItooResult.build(ItooResult.FAIL, "传入的文件为空！");
            }
            //EXCEL解析成List
            Map<Serializable, Serializable> map = new HashMap<>(4);
            map.put(SHEET_NAME, "党政部门");
            map.put(CLASS, InstitutionTemplate.class);
            List<InstitutionTemplate> institutionTemplateList = ExcelUtil.importExcel(Objects.requireNonNull(fileName), map, request, response);
            if (CollectionUtils.isEmpty(institutionTemplateList)) {
                return ItooResult.build(ItooResult.FAIL, "导入的数据为空，请填写！");
            }
            //定义导入的错误数据集合并存redis中形式的<String,InstitutionTemplate>
            List<InstitutionTemplate> errorITList = new ArrayList<>();
            String errorITListId = IdWorker.getIdStr();
            Long size = redisTemplate.opsForZSet().size(errorITListId);
            size = size == null ? 0L : size;
            //循环处理数据
            for (InstitutionTemplate excelIT : institutionTemplateList) {
                if (!this.verify(excelIT)) {
                    InstitutionTemplate institutionTemplate = new InstitutionTemplate();
                    BeanUtils.copyProperties(excelIT, institutionTemplate);
                    errorITList.add(institutionTemplate);
                    redisTemplate.opsForZSet().add(errorITListId, institutionTemplate, size + 1);
                    continue;
                }
                InstitutionEntity institutionEntity = new InstitutionEntity();
                //将导入内容放到entity中对应的属性中去
                BeanUtils.copyProperties(excelIT,institutionEntity);
                //党政部门编码
                institutionEntity.setCode(excelIT.getCode());
                //党政部门名称
                institutionEntity.setName(excelIT.getName());
                //党政部门名称
                institutionEntity.setAbbreviation(excelIT.getAbbreviation());
                //备注
                institutionEntity.setRemark(excelIT.getRemark());
                //类型
                institutionEntity.setType(0);
                this.save(institutionEntity);
                this.saveToAuth(institutionEntity);
            }
            //不符合条件的信息返回
            if (!CollectionUtils.isEmpty(errorITList)) {
                return ItooResult.build("0001", "部分导入失败", errorITListId);
            }
        } catch (Exception e) {
            return ItooResult.build(ItooResult.FAIL, "导入数据异常！", e);
        }
        return ItooResult.build(ItooResult.SUCCESS, "导入数据成功！");
    }

    /**
     * 判断批量导入的信息是否符合要求
     *
     * @param institutionTemplate 需要导入的信息
     * @return boolean 导入的字段是否为空
     * @author 杨燕梅
     * @since 2.0.0 2018-12-1 23:21:08
     */
    private boolean verify( InstitutionTemplate institutionTemplate) {
        //判断党政部门代码是否填写
        if (StringUtils.isEmpty(institutionTemplate.getCode())) {
            institutionTemplate.setFailReason("党政部门代码未填写");
            log.warn("导入失败,党政部门代码未填写,excelInstitutionEntity-{}", institutionTemplate);
            return false;
        }
        //判断党政部门名称是否填写
        if (StringUtils.isEmpty(institutionTemplate.getName())) {
            institutionTemplate.setFailReason("党政部门名称未填写");
            log.warn("导入失败,党政部门名称未填写,excelInstitutionEntity-{}", institutionTemplate);
            return false;
        }
        //判断党政部门代码是否重复
        if (!CollectionUtils.isEmpty(institutionDao.queryByCodeAndNameExist(institutionTemplate.getCode(),institutionTemplate.getName()))){
            institutionTemplate.setFailReason("党政部门代码已存在");
            log.warn("导入失败,党政部门代码已存在,excelInstitutionEntity-{}", institutionTemplate);
            return false;
        }
        return true;
    }

    /**
     * 根据errorListId导出未成功导入的信息
     *
     * @param response    响应
     * @param errorListId 为成功导入的分组id
     * @return 导出结果
     * @author 杨燕梅
     * @since 1.0.0 2018-12-1 23:23:33
     */
    @Override
    public boolean exportErrorList(String errorListId, HttpServletResponse response){
        //redis取出没有成功导入的党政部门信息
        Set set = redisTemplate.opsForZSet().range(errorListId, 0, -1);
        List<InstitutionTemplate> institutionTemplates=new ArrayList<>(set);
        //清空redis数据
        redisTemplate.delete(errorListId);
        //导出没有成功导入的党政部门信息
        if(institutionTemplates.size()==0){
            return false;
        }
        Map<Serializable, Serializable> errorMap = new HashMap<>(16);
        errorMap.put(NAME, "未导入的党政部门信息");
        errorMap.put(SHEET_NAME, "未导入的党政部门信息");
        errorMap.put(TITLE, "未导入的党政部门信息");
        errorMap.put(COLUMNS, new String[]{"code", "name", "abbreviation", "remark", "failReason"});
        errorMap.put(DATA_LIST, (Serializable) institutionTemplates);
        try {
            ExcelUtil.exportExcel(errorMap, response);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 根据党政部门代码和党政部门名称查询党政部门是否已存在
     *
     * @param code   党政部门代码
     * @param name   党政部门名称
     * @return 党政部门信息
     * @author 杨燕梅
     * @since 2.0.0 2018-12-20 09:05:59
     */
    @Override
    public List<InstitutionEntity>queryByCodeAndNameExist(String code, String name){
        return institutionDao.queryByCodeAndNameExist(code,name);
    }
    /**
     * 将数据保存到权限中去
     *
     * @param institutionEntity
     * @author 李建帅
     * @since 2.0.0 2018-12-9 19:18:10
     */
    @Override
    public void saveToAuth(InstitutionEntity institutionEntity){
//        List<OrganizationEntity> organizationEntityList = new ArrayList<>();
//        OrganizationEntity organizationEntity = new OrganizationEntity();
//        organizationEntity.setId(institutionEntity.getId());
//        organizationEntity.setOrganizationName(institutionEntity.getName());
//        organizationEntity.setPId("87LkGQNeDpE7H6paYhZ7zZ");
//        organizationEntity.setCompanyId("lfsfxy111222");
//        organizationEntityList.add(organizationEntity);
//        organizationFacade.synchroOrganization(organizationEntityList);
//
//        try {
//            organizationFacade.synchroOrganization(organizationEntityList);
//        } catch (Exception e) {
//            log.error("将组织机构信息同步到权限中心失败！", e);
//        }
    }
}
